/*
 * Copyright 2011 Shotaro Uchida <fantom@xmaker.mx>.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jazzkaffe;

/**
 * ZigBee NWK Address
 * @author Shotaro Uchida <fantom@xmaker.mx>
 */
public class NetworkAddress extends ZigBeeAddress {
    
    public static final int ADDRESS_SIZE = 2;
    public static final NetworkAddress BROADCAST_ALL = new NetworkAddress(new byte[] {(byte) 0xFF, (byte) 0xFF});
    public static final NetworkAddress BROADCAST_MROWI = new NetworkAddress(new byte[] {(byte) 0xFD, (byte) 0xFF});
    public static final NetworkAddress BROADCAST_ZR_ZC = new NetworkAddress(new byte[] {(byte) 0xFC, (byte) 0xFF});
    public static final NetworkAddress BROADCAST_LOW_ZR = new NetworkAddress(new byte[] {(byte) 0xFB, (byte) 0xFF});
    
    protected NetworkAddress(byte[] addr16) {
        super(addr16, ADDRESS_SIZE);
    }
    
    public static NetworkAddress getByAddress(byte[] addr16) {
        return new NetworkAddress(addr16);
    }
    
    public static NetworkAddress getByAddress(short address) {
        byte[] addr16 = new byte[ADDRESS_SIZE];
        addr16[0] = (byte) (address & 0xFF);
        addr16[1] = (byte) ((address >> 8) & 0xFF);
        return new NetworkAddress(addr16);
    }
    
    public boolean isBroadcast() {
        return ((mac[1] & 0xFF) == 0xFF) && ((mac[0] & 0xFF) >= 0xF8);
    }
    
    public String toString() {
        return Integer.toHexString(toShort() & 0xFFFF);
    }
    
    public short toShort() {
        return (short) ((mac[1] & 0xFF) << 8 | (mac[0] & 0xFF));
    }
}
